<?php
/*
Plugin Name: zhihu
Plugin URI: http://www.hengha.info
Description: Crawl question from http://www.zhihu.com
Version: 1.0
Author: tomcat
Author URI: http://www.hengha.info
Text Domain: zhihu
Domain Path: /languages/
*/

require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
require_once(ABSPATH . 'wp-includes/taxonomy.php');
function zhihu_add_small_interval($schedules)
{
    if (!isset($schedules['ten-minutes'])) {
        $schedules['ten-minutes'] = array(
            'interval' => 600,
            'display' => __('Ten Minutes', 'qiushibaike')
        );
    }
    if (!isset($schedules['three-minutes'])) {
        $schedules['three-minutes'] = array(
            'interval' => 180,
            'display' => __('Three Minutes', 'qiushibaike')
        );
    }

    return $schedules;
}

add_filter('cron_schedules', 'zhihu_add_small_interval');

/*
function load_plugin_textdomain() {
  load_plugin_textdomain( 'qiushibaike', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}

add_action( 'plugins_loaded', 'load_plugin_textdomain' );
 */

function zhihu_activation()
{
    wp_schedule_event(time(), 'ten-minutes', 'zhihu_ten_minutes_event_hook');
    wp_schedule_event(time(), 'three-minutes', 'zhihu_three_minutes_event_hook');
}

register_activation_hook(__FILE__, 'zhihu_activation');

function zhihu_get_anonymous_user_id()
{
    $userId = username_exists('zhihu');
    if ($userId == null) {
        $userId = wp_insert_user(array(
            'user_login' => 'zhihu',
            'user_email' => 'zhihu@hengha.info',
            'nickname' => '知乎',
            'display_name' => '知乎',
            'user_pass' => wp_generate_password(20),
            'role' => 'subscriber'
        ));
    }
    return $userId;
}

function zhihu_get_user_id($user)
{
    if ($user && $user->name != '匿名') {
        $login = 'zhihu_' . $user->slug;
        $userId = username_exists($login);// TODO: use email to identity
        if ($userId == null) {
            $userId = wp_insert_user(array(
                'nickname' => $user->name,
                'display_name' => $user->name,
                'user_login' => $login,
                'user_email' => $user->slug . '@zhihu.com',
                'user_pass' => wp_generate_password(20),
                'role' => 'subscriber'
            ));
            update_user_meta($userId, 'avatar', $user->avatar);
        }
        return $userId;
    } else {
        return zhihu_get_anonymous_user_id();
    }
}

function zhihu_handle_tags($tag_labels)
{
    $tags = array();
    foreach ($tag_labels as $tag) {
        $m = new stdClass();
        $m->name = trim($tag->textContent);
        $m->slug = str_replace('/topic/', '', $tag->attributes->getNamedItem('href')->nodeValue);
        $cat = get_term_by('slug', $m->slug, 'question_category');
        if ($cat) {
            $cat_id = $cat->term_id;
            wp_insert_category(array(
                'cat_ID' => $cat->term_id,
                'cat_name' => $m->name,
                'category_nicename' => $m->slug,
                'taxonomy' => 'question_category'
            ));
        } else {
            $cat_id = wp_insert_category(array(
                'cat_name' => $m->name,
                'category_nicename' => $m->slug,
                'taxonomy' => 'question_category'
            ));
        }
        $m->id = $cat_id;

        $tags[$m->id] = $m;
    }
    return $tags;
}

function zhihu_parse_answers($doc)
{
    $answers = array();
    $wrap = $doc->getElementById('zh-question-answer-wrap');

    foreach ($wrap->childNodes as $answer) {
        if ($answer->nodeName != 'div') {
            continue;
        }
        $model = new stdClass();
        $model->user = new stdClass();
        $model->slug = $answer->attributes->getNamedItem('data-aid')->nodeValue;
        $answer_header = $answer->getElementsByTagName('h3')->item(0);

        if (trim($answer_header->textContent) != '匿名用户') {
            $anchors = $answer_header->getElementsByTagName('a');
            $model->user->slug = str_replace('/people/', '', $anchors->item(0)->attributes->getNamedItem('href')->nodeValue);
            $model->user->avatar = $anchors->item(0)->getElementsByTagName('img')->item(0)->attributes->getNamedItem('src')->nodeValue;
            $model->user->name = $anchors->item(1)->textContent;
        } else {
            $model->user->name = '匿名';
        }
        $model->content = '';
        foreach ($answer->childNodes as $child) {
            if ($child->nodeName == 'div') {
                $styles = $child->attributes->getNamedItem('class');
                if ($styles && $styles->nodeValue == 'zm-item-rich-text') {
                    $model->content = $child->C14N();
                    break;
                }
            }
        }
        $answers[] = $model;
    }
    return $answers;
}

function zhihu_save_answers($answers, $question_id)
{
    $reply_args = array(
        'post_type' => 'question-reply',
        'posts_per_page' => 1,
    );

    foreach ($answers as $answer) {
        $question_args['name'] = $answer->slug;
        $reply_query = new WP_Query($reply_args);
        if ($reply_query->have_posts()) {
            // TODO: update post
        } else {
            $author_id = zhihu_get_user_id($answer->user);
            $reply_id = wp_insert_post(array(
                'post_content' => $answer->content,
                'post_title' => $answer->user->name,
                'post_name' => $answer->slug,
                'post_author' => $author_id,
                'post_type' => 'question_reply'
            ));
            update_post_meta($reply_id, 'reply_type', 'answer');
            update_post_meta($reply_id, 'reply_object', $question_id);
        }
    }
}

function get_answsers()
{
    $args = array(
        'user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120
    );
    $question_args = array(
        'post_type' => 'question',
        'post_status' => 'draft',
        'posts_per_page' => 1,
        'orderby' => 'ID',
        'order' => 'ASC',
        'meta_key' => 'source',
        'meta_value' => 'zhihu',
    );
    $question_query = new WP_Query($question_args);

    foreach ($question_query->posts as $question) {
        var_dump($question);
        $url = get_post_meta($question->ID, 'source_url', true);
        if ($url) {
            wp_update_post(array(
                'ID' => $question->ID,
                'post_status' => 'process'
            ));
            $author_id = zhihu_get_anonymous_user_id();
            $item_id = substr($url, strripos($url, '/') + 1);
            $content = wp_remote_get($url, $args);
            $dom = new DOMDocument();
            $dom->loadHTML($content['body']);
            $xpath = new DOMXPath($dom);
            $header = $dom->getElementsByTagName('h2')->item(0);
            $tag_labels = $xpath->query('//a[@class="zm-item-tag"]');
            $tags = zhihu_handle_tags($tag_labels);

            var_dump($tags);
            $title = trim($header->textContent);
            $body = $dom->getElementById('zh-question-detail');
            $post_content = '';
            if ($body) {
                $post_content = $body->C14N();
            }
            wp_update_post(array(
                'ID' => $question->ID,
                'post_content' => $post_content,
                'post_title' => $title,
                'post_name' => $item_id,
                'post_author' => $author_id
            ));
            wp_set_object_terms($question->ID, array_keys($tags), 'question_category');
            //wp_publish_post($question->ID);
            $answers = zhihu_parse_answers($dom);
            zhihu_save_answers($answers, $question->ID);
        }
    }
}

function get_zhihu_comments()
{
    global $wpdb;
    $gmnow = gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
    $id = $wpdb->get_var($wpdb->prepare("select max(a.ID) from $wpdb->posts a where a.post_date_gmt>=%s and not exists(select 1 from $wpdb->comments b where b.comment_post_ID=a.ID) and a.post_type='joke' and a.post_status='publish' ", $gmnow));
    if ($id) {
        $item_id = $wpdb->get_var($wpdb->prepare("select post_title from $wpdb->posts where ID=%d", $id));
        if ($item_id) {
            add_post_meta($id, 'last-check-comments', time(), true) or update_post_meta($id, 'last-check-comments', time(), true);
            $i = 2;
            $total = handle_comments($item_id, $id);
            while ($i <= $total) {
                handle_comments($item_id, $id, $i);
                $i++;
            }
        }
    }
}

function zhihu_handle_comments($id, $post_id, $page = 1)
{
    $args = array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120);

    $content = wp_remote_get(sprintf('http://m2.qiushibaike.com/article/%d/comments?page=%d&count=50', $id, $page), $args);
    if (is_wp_error($content)) {
        error_log(sprintf("request %d,%d,%d failed", $id, $post_id, $page));
        return;
    }
    $comments = json_decode($content['body']);
    $results = array();

    foreach ($comments->items as $comment) {
        $item = array(
            'comment_post_ID' => $post_id,
            'comment_approved' => 1,
            'comment_parent' => 0,
        );
        $item['comment_author_IP'] = $comment->id;
        $item['comment_content'] = $comment->content;
        $item['comment_date'] = current_time('mysql');

        $user_id = 0;

        $user_id = get_user_id($comment->user);

        $item['user_id'] = $user_id;
        $results[] = $item;
    }
    save_comments($results);
    return $comments->total;
}

function zhihu_save_comments($comments)
{
    global $wpdb;
    foreach ($comments as $comment) {
        $temp = $wpdb->get_var($wpdb->prepare("select meta_id from $wpdb->commentmeta where meta_key='qiushibaike-comment-id' and meta_value=%s", $comment['comment_author_IP']));
        if (!$temp) {
            $id = wp_insert_comment($comment);
            add_comment_meta($id, 'qiushibaike-comment-id', $comment['comment_author_IP']);
        }
    }
}


function zhihu_get_answers($attrs)
{
    get_answsers();
}

add_shortcode('zhihu', 'zhihu_get_answers');
//add_shortcode('qiushibaike-comments', 'qiushibaike_comments');


//add_action('zhihu_ten_minutes_event_hook', 'get_answsers');
//add_action('zhihu_three_minutes_event_hook', 'get_zhihu_comments');
function zhihu_deactivation()
{
    wp_clear_scheduled_hook('zhihu_ten_minutes_event_hook');
    wp_clear_scheduled_hook('zhihu_three_minutes_event_hook');
}

register_deactivation_hook(__FILE__, 'zhihu_deactivation');
?>
